//
//  TopicViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/12/27.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "TopicViewController.h"
#import "Topic.h"

@interface TopicViewController () <UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *infoArr;
@property (nonatomic, assign) NSInteger page; // 网络请求页数

@property (nonatomic, strong) NSString *keyWord;

@end

@implementation TopicViewController {
    UISearchBar     *_searchBar;
    UIView          *_line1;
    
    UITableView     *_tableView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.keyWord = @"";
    
    self.page = 1;
    
    [self buildUI];
    
    
}

- (void)buildUI {
    
    self.view.backgroundColor = kWhiteColor;
    
    self.navigationItem.title = @"话题";
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(SW(20), SW(40), SCREEN_WIDTH-SW(10), SW(10))];
    _searchBar.keyboardType = UIKeyboardTypeDefault;
    _searchBar.delegate = self;
    // 底部的颜色
    _searchBar.barTintColor = [UIColor whiteColor];
    _searchBar.layer.borderWidth = 1;
    _searchBar.layer.borderColor = RGBA(236, 236, 236, 1).CGColor;
    _searchBar.layer.cornerRadius = SW(20);
    _searchBar.layer.masksToBounds = YES;
    _searchBar.searchBarStyle = UISearchBarStyleDefault;
    _searchBar.barStyle = UIBarStyleBlack;
    [self.view addSubview:_searchBar];
//    [_searchBar becomeFirstResponder];
    
    _line1 = [[UIView alloc] initWithFrame:CGRectMake(0, _searchBar.y+_searchBar.height+SW(40), SCREEN_WIDTH, 1)];
    [self.view addSubview:_line1];
    _line1.backgroundColor = UISeparatedColorRGB;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SW(20)*3+1, SCREEN_WIDTH, SCREEN_HEIGHT-65-SW(20)*3) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    //    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableFooterView = [[UIView alloc]init];
    
    [self refreshData];
    
}

#pragma mark ==========UISearchBar 代理响应方法==========
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    return YES;
}
//- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
//    return YES;
//}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    NSLog(@"开始输入搜索内容");
    
    // 取消字体颜色？
    searchBar.showsCancelButton = YES;
    [searchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    NSLog(@"输入搜索完毕");
    
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"取消搜索");
    
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"搜索");
    [searchBar resignFirstResponder];
    
    NSString *word = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (word.length == 0) {
        [self presentViewController:[LZCTools alertMessage:@"请输入关键字"] animated:YES completion:nil];
        return;
    }
    
    self.page = 1;
    self.keyWord = word;
    
    //    if (self.keyWord.length > 6) {
    //        self.keyWord = [self.keyWord substringToIndex:6];
    //    }
    
    _searchBar.text = self.keyWord;
    
    [self searchB];
    
}

- (void)searchB {
    
    [self GETTopic];
}


#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
//    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        NSLog(@"下拉刷新");
//        weakSelf.page = 1;
//        [weakSelf GETTopic];
//        
//    }];
//    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETTopic];
    }];
    
}

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    
    Topic *model = self.infoArr[indexPath.row];
    
    cell.textLabel.text = model.name;
    cell.textLabel.textColor = kGrayColor;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"约%ld个动态", model.count];

    return  cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
    
    Topic *model = self.infoArr[indexPath.row];
    
    [self.navigationController popViewControllerAnimated:YES];
    
    if (self.returnTopic != nil) {
        self.returnTopic(@{@"name":model.name});
    }
}

- (void)returnTopic:(ReturnTopicBlock)block {
    self.returnTopic = block;
}

#pragma mark ==========响应方法==========
- (void)GETTopic {
    
    NSString *url = [NSString stringWithFormat:@"%@/tags", APIPosts];
    NSDictionary *param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
                            @"per_page":@"30",
                            @"keyword":self.keyWord};
    [[NetworkTool sharedTool] requestWithName:@"获取话题" URLString:url parameters:param method:@"GET" callBack:^(id responseObject) {
        
        NSMutableArray *arr = [[NSMutableArray alloc] initWithArray:responseObject[@"data"]];
        
        if (self.page == 1) {
            [self.infoArr removeAllObjects];
            if (arr.count == 0) {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"没有这个话题，是否创建" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"不" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:@"是的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self.navigationController popViewControllerAnimated:YES];
                    
                    if (self.returnTopic != nil) {
                        self.returnTopic(@{@"name":self.keyWord});
                    }
                }]];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }
        
        if (arr.count == 0) {
            self.page--;
        }
        
        for (NSDictionary *dic in arr) {
            Topic *model = [[Topic alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.infoArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        });
    }];
    
}

// 懒加载
- (NSMutableArray *)infoArr {
    if (_infoArr == nil) {
        _infoArr = [[NSMutableArray alloc] init];
    }
    return _infoArr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
